<template>
	<div class="app-todo-list">
		<a-input-search
			class="app-todo-list__search"
			v-model:value="query"
			:placeholder="$t('common.todolist.caption')"
			enter-button
			@search="handleSearch"
		/>
		<a-table
			class="app-todo-list__table"
			:columns="columns"
			:dataSource="myTasks"
			:pagination="pagination"
			:scroll="scrollOptions"
			@change="handleGridChange"
		>
			<template #bodyCell="{ column, text, record }">
				<template v-if="column.dataIndex == 'description'">
					<a @click="handleClick(record)">{{ text }}</a>
				</template>
			</template>
			<template #emptyText>
				<AppEmptyDataTip
					:emptyText="$t('common.todolist.emptytext')"
				></AppEmptyDataTip>
			</template>
		</a-table>
	</div>
</template>

<script setup lang="ts">
import { Ref, ref } from 'vue';
import { Http } from '@/http';
import { IParam, createUUID } from '@/core';
import { router } from '@/router';
import { getIndexRoutePath } from '@/utils';

let query: Ref<string> = ref('');

let myTasks: Ref<any[]> = ref([]);

let limit: Ref<number> = ref(20);

let curPage: Ref<number> = ref(1);

let total: Ref<number> = ref(0);

let sort: string = '';

const columns: IParam[] = [
	{
		title: App.ts('common.todolist.caption'),
		dataIndex: 'description',
		sorter: true,
	},
	{
		title: App.ts('common.todolist.flow'),
		dataIndex: 'processDefinitionName',
		sorter: true,
		width: '200px',
	},
	{
		title: App.ts('common.todolist.state'),
		dataIndex: 'name',
		sorter: true,
		width: '200px',
	},
	{
		title: App.ts('common.todolist.createtime'),
		dataIndex: 'createTime',
		sorter: true,
		width: '200px',
	},
];

const scrollOptions = ref({
	scrollToFirstRowOnChange: true,
	x: '100%',
	y: '100%',
});

const pagination = computed(() => ({
	defaultPageSize: 20,
	total: total.value,
	current: curPage.value,
	pageSize: limit.value,
	position: ['bottomRight'],
	showSizeChanger: true,
	pageSizeOptions: ['10', '20', '50', '100'],
	showQuickJumper: true,
}));

const ability: any = {
	name: 'app-todo-list' + createUUID(),
	refresh: (arg?: any) => {
		getMyTasks();
	},
};

App.getGlobalNotificationHelper().setAbility('srfwftodo', ability);

const getMyTasks = () => {
	const params = {
		size: limit.value,
		page: curPage.value - 1,
	};
	let url: string = '/wfcore/mytasks';
	if (query.value) {
		Object.assign(params, { query: query.value });
	}
	if (sort) {
		Object.assign(params, { sort: sort });
	}
	Http.getInstance()
		.get(url, params)
		.then((response: any) => {
			if (response.success) {
				if (response.config && response.config && response.config['x-total']) {
					total.value = Number(response.config['x-total']);
				}
				myTasks.value = response.data || [];
			}
		})
		.catch((error: any) => {
			App.getNotificationHelper().error(
				App.ts('app.notificationtitle.error'),
				error.message ? error.message : App.ts('common.todolist.error')
			);
		});
};

const handleClick = (data: IParam) => {
	if (
		!data ||
		!data.processDefinitionKey ||
		!data.processInstanceBusinessKey ||
		!data.taskDefinitionKey
	) {
		App.getNotificationHelper().error(
			App.ts('app.notificationtitle.error'),
			App.ts('common.todolist.skiperror')
		);
		return;
	}
	const srfappde = (data.processDefinitionKey as string).split('-')[1];
	const url = `/appwfdataredirectview?srfappde=${srfappde};srfappkey=${data.processInstanceBusinessKey};userTaskId=${data.taskDefinitionKey}`;
	const { currentRoute, push } = router;
	const indexPath = getIndexRoutePath(currentRoute.value);
	push(`${indexPath}${url}`);
};

const handleSearch = () => {
	getMyTasks();
};

const handleGridChange = (
	pagination: IParam,
	filters: IParam,
	sorter: IParam,
	data: IParam
) => {
	//  分页变化
	if (pagination) {
		if (pagination.current !== curPage.value) {
			curPage.value = pagination.current;
		}
		if (pagination.pageSize !== limit.value) {
			limit.value = pagination.pageSize;
		}
	}
	//  排序变化
	if (sorter) {
		const { field, order } = sorter;
		if (field) {
			const dir = Object.is(order, 'ascend')
				? 'asc'
				: Object.is(order, 'descend')
				? 'desc'
				: '';
			sort = dir ? `${field},${dir}` : '';
		}
	}
	if (pagination || sorter) {
		getMyTasks();
	}
};

getMyTasks();

onUnmounted(() => {
	App.getGlobalNotificationHelper().destroyAbility('srfwftodo', ability);
});
</script>
